package thread_test;

// 测试 notify() 方法功能
public class NotifyDemo {
    public static void main(String[] args) {
        // 创建一个锁对象
        Object object = new Object();
        Thread t1 = new Thread(()->{
            synchronized (object) {
                System.out.println(" wait 之前");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(" wait 之后");
            }
        });
        Thread t2 = new Thread(()->{
            // 让 t2 线程先休眠 2s 是为了让 t1 线程先执行到 wait() 方法
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (object){
                System.out.println("使用 notify 唤醒 wait");
                object.notify();
                // 这里休眠两秒是为了观察调用完 notify() 方法后会不会立即释放锁对象
                System.out.println("休眠 2 秒观察");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        // 启动两个线程
        t1.start();
        t2.start();
    }
}
